#include "stdafx.h"
#include "SigSource.h"
#include "SigSite.h"

using namespace Base::Sig;

SigSource::SigSource()
{
}

SigSource::~SigSource()
{
    for(unsigned int i = 0; i < m_sigSites.size(); ++i)
    {
        SigSite* sigSite = m_sigSites[i];
        assert(sigSite);
        
        sigSite->sigSource(0);
    }
    
    m_sigSites.clear();
}

void
SigSource::hook(SigSite* sigSite)
{
    const int index = indexOf(sigSite);
    if (sigSite && index < 0)
    {
        m_sigSites.push_back(sigSite);
        sigSite->sigSource(this);
    }
}

void
SigSource::unhook(SigSite* sigSite)
{
    const int index = indexOf(sigSite);
    if (sigSite && index > -1)
    {
        m_sigSites.erase(m_sigSites.begin() + index);
        sigSite->sigSource(0);
    }
}

bool
SigSource::hookedWith(SigSite* sigSite) const
{
    return (   sigSite
            && indexOf(sigSite) > -1);
}

bool
SigSource::hooked() const
{
    return !m_sigSites.empty();
}

void
SigSource::send(Signal* signal)
{
    for(unsigned int i = 0; i < m_sigSites.size(); ++i)
    {
        SigSite* sigSite = m_sigSites[i];
        assert(sigSite);
        
        sigSite->receive(signal);
    }
}

int
SigSource::indexOf(SigSite* sigSite) const
{
    if (sigSite)
    {
        SigSites::const_iterator it = std::find(m_sigSites.begin(), 
                                                m_sigSites.end(), 
                                                sigSite);
        if (it != m_sigSites.end())
            return (it - m_sigSites.begin());
    }
        
    return -1;
}